<!-- 翻页表格组件 -->
<template>
  <a-table
    ref="tableRef"
    :data="tableList"
    :pagination="isShowPagination && pagination"
    @page-change="pageChange($event, 'pageNumber')"
    @page-size-change="pageChange($event, 'pageSize')"
    :scroll="{
      x: width,
      y: height ? height : globalParameters.windowHeight - winHeightReduce
    }"
    v-bind="args ? { ...args } : null"
    :row-key="rowKey"
    :draggable="props.draggable"
    @select="onSelect"
    @select-all="onSelectAll"
    v-model:expanded-keys="currExpandedKeys"
    v-model:selected-keys="selectedList"
    @change="handleChange"
    :loading="isLoading"
    :stripe="true"
    :columns="props?.columns"
    column-resizable
  >
    <template #expand-icon="{ expanded }">
      <icon-down v-show="expanded" />
      <icon-right v-show="!expanded" />
    </template>
    <!-- arco-table的插槽，默认为columns -->
    <template #columns>
      <slot />
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { useGlobalParametersStore } from '@/store';
import { cloneDeep } from 'lodash';

export interface paramsType {
  // page: number;
  // size: number;
  pageNumber: number;
  pageSize: number;
}
export interface draggableType {
  type?: 'row' | 'handle'; //类型
  title?: string; //列标题
  width?: number; //列宽度
  fixed?: boolean; //是否固定
}

const globalParameters = useGlobalParametersStore();
const props = withDefaults(
  // 参数说明
  defineProps<{
    tableData: (params: paramsType) => any; // 请求table数据的函数
    width?: string | number; // 表格的实际宽度，用来显示滚轮,  有默认值
    height?: string | number; // 表格的实际高度，用来显示滚轮,  不传默认使用winHeightReduce
    args?: any; // 对象，放置a-table的剩余属性
    winHeightReduce?: number; // 表格的实际高度,height不传时使用这个, 计算为窗口高度减去值，有默认值
    isShowPagination?: boolean; // 是否显示分页
    rowKey?: string; // 行的唯一标识，默认为改行的id
    expandedKeys?: any; // 默认展开的行
    draggable?: draggableType; // 表格拖拽
    columns?: any; // 自定义列
  }>(),
  {
    width: '100%',
    winHeightReduce: 300,
    isShowPagination: true,
    args: {
      // bordered: {
      //   headerCell: true
      // }
      // stripe: true
    },
    rowKey: 'id',
    columns: []
  }
);
let tableRef = ref();

let isLoading = ref(true); // 判断表格是否处于加载数据状态

const pagination = reactive({
  // 分页数据
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [20, 30, 40, 50, 100],
  current: 0,
  total: 0,
  pageNumber: null,
  pageSize: null
});
const params = reactive({
  // 分页数据，用于请求
  pageNumber: 0,
  pageSize: 20
});
const tableList = ref<any>([]); // 储存表格数据
const selectedList = ref<any>([]); // 储存选中的数据
const selectedListData = ref<any>([]); // 储存选中的数据

let currExpandedKeys = ref([]); // 储存展开的树形结构

// 加载表格数据
const loadData = async (pageData?: {
  pageSize: number;
  pageNumber: number;
}) => {
  let res;
  if (pageData) res = await props.tableData(pageData);
  else res = await props.tableData(params);
  isLoading.value = false;
  const { content, pageable } = res;
  if (pageable) {
    pagination.current = pageable.pageNumber;
    pagination.total = pageable.totalItems;
    pagination.pageSize = pageable.pageSize;
    tableList.value = content;
  } else {
    tableList.value = res;
  }

  if (props.draggable)
    tableList.value.sort((a: any, b: any) => a.order - b.order);
};

// 修改页码数
const pageChange = (val: number, key: 'pageNumber' | 'pageSize') => {
  params[key] = val - 1;
  loadData();
};
loadData();

// 选择数据事件
const onSelect = (rowKeys: any, rowKey: any, record: any) => {
  if (props.args.rowSelection.type === 'radio') {
    selectedListData.value[0] = record;
    return;
  }
  const index = selectedList.value.findIndex((item: any) => {
    return item === rowKey;
  });
  if (index === -1) {
    selectedList.value.push(record);
    selectedListData.value.push(record);
  } else {
    selectedList.value.splice(index, 1);
    selectedListData.value.splice(index, 1);
  }
  // console.log('====================================');
  // console.log('asdasdsa', selectedList.value);
  // console.log('====================================');
};

// 全选按钮
const onSelectAll = (checked: boolean) => {
  if (checked) {
    selectedList.value = [...selectedList.value, ...cloneDeep(tableList.value)];
    selectedListData.value = [
      ...selectedListData.value,
      ...cloneDeep(tableList.value)
    ];
  } else {
    selectedList.value = [];
    selectedListData.value = [];
  }
};
// 拖拽表格
const handleChange = (_data: any) => {
  _data.forEach((ele: any, ind: number) => {
    ele.order = ind + 1;
  });
  tableList.value = _data;
  emit('handleChange', tableList.value);
};

// 树形结构用来展开第几级
const expandTree = (rowKey: any) => {
  // console.log('====================================');
  console.log(rowKey);
  // console.log('====================================');
  currExpandedKeys.value = rowKey;
};

/*
  对外暴露loadData和tableList
  loadData: 用来更新表格数据，可以在模糊搜索时使用
  tableList: 用来新增删除表格行数的操作，可以用来新增一行的时候使用
  selectedList: 用来暴露选中的数据数组ID
  selectedListData: 用来暴露选中的数据数组数据
*/
defineExpose({
  loadData,
  tableList,
  selectedList,
  selectedListData,
  currExpandedKeys,
  expandTree,
  tableRef
});
/**
 * handleChange  拖拽表格回调事件
 */
const emit = defineEmits(['handleChange']);
</script>

<style scoped lang="less">
:deep(.arco-table-td) {
  height: 40px;
}

:deep(.arco-table-th) {
  height: 45px;
  font-weight: 700;
}

:deep(.arco-table-cell) {
  justify-content: center;
  text-align: center;
}
// 垂直滚动条统一往外
:deep(.arco-scrollbar-track-direction-vertical) {
  right: -15px;
}
// 水平滚动条统一往外
:deep(.arco-scrollbar-track-direction-horizontal) {
  bottom: -15px;
}

// :deep(.arco-table .arco-spin) {
//   height: calc(100% - 1px);
// }
</style>
